package com.web.itemService.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.TokenInfo;
import entity.WeChatUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class changeCodeUtils {
    public WeChatUser togetAccess_token(String code) throws JsonProcessingException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxdf1c519996b434cb&secret=7711c4a5964446cd78ea3f092efa5329&code=" + code + "&grant_type=authorization_code";
        // 创建 RestTemplate
        RestTemplate restTemplate = new RestTemplate();


// 使用 getForEntity 获取响应
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        String responseBody = response.getBody();
        log.info("responseBody: {}", responseBody);
// 手动转换为 TokenInfo
        ObjectMapper objectMapper = new ObjectMapper();
        TokenInfo tokenInfo = objectMapper.readValue(responseBody, TokenInfo.class);
        String access_token = tokenInfo.getAccess_token();
        String openid = tokenInfo.getOpenid();
//TODO 这里是获取access_token 后获取信息
        String url1 ="https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token+ "&openid=" + openid+ "&lang=zh_CN";
        RestTemplate restTemplate1 = new RestTemplate();
        ResponseEntity<String> response1 = restTemplate1.getForEntity(url1, String.class);
        String responseBody1 = response1.getBody();
        log.info("拉取用户信息： {}", responseBody1);
        ObjectMapper objectMapper1 = new ObjectMapper();
        WeChatUser weChatUser = objectMapper1.readValue(responseBody1, WeChatUser.class);
        log.info("获取的用户信息是: {}", weChatUser);
        return weChatUser;
    }



}
